/*
 * @lc app=leetcode.cn id=1249 lang=javascript
 *
 * [1249] 移除无效的括号
 */

// @lc code=start
/**
 * @param {string} s
 * @return {string}
 */
var minRemoveToMakeValid = function (s) {
  let firstResult = '';
  let count = 0;
  // 第一次从左往右扫描，删除多余的右括号
  for (let i = 0; i < s.length; i++) {
    let char = s[i];
    if (char === '(') {
      firstResult += char;
      count++;
    } else if (char === ')') {
      if (count === 0) continue;
      count--;
      firstResult += char;
    } else {
      firstResult += char;
    }
  }

  let twoResult = '';
  count = 0;
  // 第一次从右往左扫描，删除多余的左括号
  for (let i = firstResult.length - 1; i >= 0; i--) {
    let char = firstResult[i];
    if (char === ')') {
      twoResult = char + twoResult;
      count++;
    } else if (char === '(') {
      if (count === 0) continue;
      count--;
      twoResult = char + twoResult;
    } else {
      twoResult = char + twoResult;
    }
  }

  return twoResult;
};
// @lc code=end
